<template>
  <div class="order-container">
    <!-- 顶部卡片区域 -->
    <div class="header-card">
      <div class="header-content">
        <h1 class="title">我的订单</h1>
        <p class="subtitle">共 {{total}} 个订单</p>
      </div>
      <div class="header-actions">
        <el-select
            v-model="filterStatus"
            placeholder="订单状态"
            class="status-filter"
            @change="handleFilterChange"
            style="--el-select-border-color-hover: #409EFF;"
        >
          <el-option label="全部订单" value=5></el-option>
          <el-option label="待付款" value=0></el-option>
          <el-option label="待发货" value=1></el-option>
          <el-option label="待收货" value=2></el-option>
          <el-option label="已完成" value=3></el-option>
          <el-option label="已取消" value=4></el-option>
        </el-select>
        <el-button
            type="primary"
            class="refresh-btn"
            @click="fetchOrders"
            :icon="Refresh"
            circle
            size="large"
        />
      </div>
    </div>

    <!-- 主订单卡片 -->
    <div class="main-card">
      <div class="card-header">
        <h3>订单列表</h3>
        <div class="card-extra">
          <span>当前显示: {{orderData.orders.length}} 条</span>
        </div>
      </div>

      <el-table
          :data="orderData.orders"
          style="width: 100%"
          stripe
          v-loading="orderData.loading"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.7)"
          class="order-table"
          :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      >
        <el-table-column type="index" :index="indexMethod" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="orderNo" label="订单编号" width="220" align="center">
          <template #default="scope">
            <span class="order-no">{{scope.row.orderNo}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="收货人" width="90" align="center"></el-table-column>
        <el-table-column prop="contactPhone" label="电话" width="130" align="center"></el-table-column>
        <el-table-column prop="actualAmount" label="实付款" width="100" align="center">
          <template #default="scope">
            <span class="price">¥{{scope.row.actualAmount.toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单总金额" width="120" align="center">
          <template #default="scope">
            <span>¥{{scope.row.totalAmount.toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="150" align="center">
          <template #default="scope">
            <el-tag
                :type="getStatusTagType(scope.row.status)"
                effect="light"
                class="status-tag"
            >
              <div v-if="scope.row.status == 0">
                <span>未付款</span>
                <el-button
                    type="primary"
                    size="small"
                    plain
                    @click="()=>{getParam(getUserId(),scope.row.orderNo,scope.row.status+1),dialogVisible1=true}"
                    class="action-btn"
                >
                  付款
                </el-button>
              </div>
              <div v-else>
                {{ statusFormatter(scope.row.status) }}
              </div>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费" width="90" align="center">
          <template #default="scope">
            <span>¥{{scope.row.freight.toFixed(2)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentType" label="支付方式" width="120" align="center"
                         :formatter="paymentTypeFormatter"></el-table-column>
        <el-table-column prop="paymentTime" label="支付时间" width="160" align="center"></el-table-column>
        <el-table-column prop="shippingAddress" label="收货地址" width="180" align="center"></el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="160" align="center"></el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  type="text"
                  size="small"
                  @click="() => { viewOrderDetail(scope.row.id); dialogVisible=true }"
                  class="action-btn detail-btn"
              >
                <el-icon><View /></el-icon>详情
              </el-button>
              <el-button
                  type="text"
                  :disabled="scope.row.status != 2"
                  @click="()=>{getParam(getUserId(),scope.row.orderNo),ConfirmReceipt()}"
                  class="action-btn"
              >
                <el-icon><Check /></el-icon>收货
              </el-button>
              <el-button
                  type="text"
                  size="small"
                  @click="deleteOrder(getUserId(),scope.row.orderNo,scope.row.status)"
                  class="action-btn delete-btn"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="orderData.currentPage"
            v-model:page-size="orderData.pageSize"
            :total="orderData.total"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            class="pagination"
        />
      </div>
    </div>
  </div>

  <!-- 订单详情弹窗 -->
  <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      :before-close="handleClose"
      width="60%"
      class="detail-dialog"
  >
    <div class="dialog-header">
      <h3>订单商品</h3>
    </div>
    <el-table
        :data="orderItems"
        stripe
        row-key="id"
        element-loading-background="rgba(255, 255, 255, 0.7)"
        class="detail-table"
    >
      <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="productName" label="商品名称" width="200" align="center"></el-table-column>
      <el-table-column prop="productImage" label="商品图片" width="180" align="center">
        <template #default="scope">
          <img
              :src="scope.row.productImage"
              class="product-image"
          >
        </template>
      </el-table-column>

      <el-table-column prop="price" label="商品价格" width="120" align="center">
        <template #default="scope">
          <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="quantity" label="商品数量" width="120" align="center"></el-table-column>

      <template #empty>
        <el-empty description="暂无订单数据"></el-empty>
      </template>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 付款弹窗 -->
  <el-dialog
      title="确认付款"
      v-model="dialogVisible1"
      :before-close="handleClose"
      width="400px"
      class="pay-dialog"
  >
    <div class="pay-content">
      <el-form>
        <el-form-item label="请选择付款方式" class="pay-method">
          <el-select v-model="param.paymentType" placeholder="选择支付方式">
            <el-option label="微信" value=1>
              <div class="pay-option">
                <img src="https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/zh/images/logo.svg" class="pay-icon">
                <span>微信</span>
              </div>
            </el-option>
            <el-option label="支付宝" value=2>
              <div class="pay-option">
                <img src="https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/zh/images/logo.svg" class="pay-icon">
                <span>支付宝</span>
              </div>
            </el-option>
            <el-option label="银行卡" value=3>
              <div class="pay-option">
                <img src="https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/zh/images/logo.svg" class="pay-icon">
                <span>银行卡</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div class="pay-actions">
        <el-button @click="cancelPay" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="pay" class="confirm-btn">确认付款</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { Refresh, View, Check, Delete } from '@element-plus/icons-vue'
import axios from "axios";

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',    // 未付款
    1: 'warning',   // 待发货
    2: 'info',      // 待收货
    3: 'success',   // 已完成
    4: ''           // 已取消
  };
  return typeMap[status] || '';
}

//定义收货的方法
const ConfirmReceipt = () => {
  param.value.status=3;
  param.value.paymentType=null;
  axios.post(BASE_URL+'/api/v1/order/private/revise',param.value).then((response)=>{
    if (response.data.code == 2000){
      ElNotification({
        title: '操作成功',
        message: '确认收货成功！',
        type: 'success',
        position: 'top-right'
      });
      fetchOrders();
    }
  });
}

//定义删除订单的方法
const deleteOrder = (userId,orderNo,status) => {
  if (status!=3 && status!=4){
    ElMessageBox.confirm('该订单尚未完成，确定要删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      axios.post(BASE_URL+'/api/v1/order/public/delete',{userId,orderNo}).then((response)=>{
        if (response.data.code == 2000){
          ElNotification({
            title: '操作成功',
            message: '订单删除成功！',
            type: 'success',
            position: 'top-right'
          });
          fetchOrders();
        }else {
          ElMessage.error('删除失败',response.data.msg);
        }
      });
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  }else {
    axios.post(BASE_URL+'/api/v1/order/public/delete',{userId,orderNo}).then((response)=>{
      if (response.data.code == 2000){
        ElNotification({
          title: '操作成功',
          message: '订单删除成功！',
          type: 'success',
          position: 'top-right'
        });
        fetchOrders();
      }else {
        ElMessage.error('删除失败',response.data.msg);
      }
    });
  }
  fetchTotalOrders(); //获取总数
}

//定义取消支付的方法
const cancelPay = () => {
  ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    dialogVisible1.value = false;
    param.value.status=4;
    param.value.paymentType=null;
    axios.post(BASE_URL+'/api/v1/order/private/revise',param.value).then((response)=>{
      if (response.data.code == 2000){
        ElNotification({
          title: '操作成功',
          message: '已取消支付',
          type: 'info',
          position: 'top-right'
        });
        fetchOrders();
        dialogVisible1.value=false;
      }
    });
    param.value = {};
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

//定义保存付款参数的对象
const param = ref({
  userId:null,
  orderNo:null,
  status:null,
  paymentType:null
})
//获取付款参数
const getParam = (userId,orderNo,status) => {
  param.value.userId = userId;
  param.value.orderNo = orderNo;
  param.value.status = status;
}

//定义获取当前用户id的方法
const getUserId = ()=> {
  return getUser().id;
}
//定义付款的方法
const pay = () => {
  if (!param.value.paymentType) {
    ElMessage.warning('请选择支付方式');
    return;
  }

  axios.post(BASE_URL+'/api/v1/order/private/revise',param.value).then((response)=>{
    if (response.data.code == 2000){
      ElNotification({
        title: '付款成功',
        message: '您的订单已支付成功！',
        type: 'success',
        position: 'top-right'
      });
      fetchOrders();
      dialogVisible1.value=false;
    }else {
      ElMessage.error('付款失败',response.data.msg);
    }
  })
}

//定义窗口初始开关状态
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
//定义窗口开关的方法
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
}

// 订单数据响应式对象
const orderData = ref({
  allOrders: [],    // 所有订单数据
  orders: [],       // 当前页显示的订单数据
  currentPage: 1,   // 当前页码
  pageSize: 10,     // 每页大小
  total: 0,         // 总订单数
  loading: false    // 加载状态
});

const paymentTypeFormatter = (row, column, cellValue) => {
  // 根据 paymentType 的值返回不同的字符串
  switch (cellValue) {
    case 1:
      return '微信支付';
    case 2:
      return '支付宝支付';
    case 3:
      return '银行卡支付';
    default:
      return '未支付';
  }
}

const indexMethod = (index) => {
  return (orderData.value.currentPage - 1) * orderData.value.pageSize + index + 1;
}

const filterStatus = ref(null); // 筛选状态

// 订单状态格式化
const statusFormatter = (status) => {
  // 确保处理的是数字类型
  const statusMap = {
    0: '未付款',
    1: '已付款,等待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  };
  return statusMap[status] || '未知状态';
}

//定义保存商品详情的数组
const orderItems = ref([]);
// 查看订单详情
const viewOrderDetail = (orderId) => {
  console.log('查看订单详情:', orderId);
  axios.get(BASE_URL + '/api/v1/order/detail?orderId=' + orderId).then((response) => {
    if (response.data.code == 2000) {
      orderItems.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 处理筛选状态变化
const handleFilterChange = () => {
  orderData.value.currentPage = 1; // 重置到第一页
  fetchOrders();
}

// 处理页码变化
const handleCurrentChange = (val) => {
  orderData.value.currentPage = val;
  applyPagination(); // 前端分页只需重新分页，不需要重新请求
}

// 处理每页大小变化
const handleSizeChange = (val) => {
  orderData.value.pageSize = val;
  orderData.value.currentPage = 1; // 重置到第一页
  applyPagination(); // 前端分页只需重新分页，不需要重新请求
}

// 应用分页逻辑
const applyPagination = () => {
  const start = (orderData.value.currentPage - 1) * orderData.value.pageSize;
  const end = start + orderData.value.pageSize;
  orderData.value.orders = orderData.value.allOrders.slice(start, end);
}

// 获取订单数据
const fetchOrders = async () => {
  orderData.value.loading = true;
  try {
    let response
    if (filterStatus.value == 5 || filterStatus.value == null) {
      // 获取全部订单（带分页参数）
      response = await axios.get(BASE_URL + '/api/v1/order/public/selectAll');
    } else {
      response = await axios.get(BASE_URL + '/api/v1/order/public/select?status=' + filterStatus.value);
    }

    if (response.data.code == 2000) {
      orderData.value.allOrders = response.data.data;
      orderData.value.total = response.data.data.length;
      applyPagination(); // 应用分页
    } else {
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取订单数据失败');
    console.error('Error fetching orders:', error);
  } finally {
    orderData.value.loading = false;
  }
}

//定义保存订单总数的对象
const total = ref(0);
//加载订单总数
const fetchTotalOrders = async () => {
  try {
    const response = await axios.get(BASE_URL + '/api/v1/order/total');
    if (response.data.code === 2000) {
      total.value = response.data.data;
    }
  } catch (error) {
    console.error('Error fetching total orders:', error);
  }
}

// 初始化加载
onMounted(() => {
  fetchOrders();
  fetchTotalOrders(); //获取总数
})
</script>

<style scoped lang="scss">
.order-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  background-color: #f5f7fa;
}

/* 顶部卡片样式 */
.header-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 25px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f4ff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;

  .header-content {
    .title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
      display: flex;
      align-items: center;

      &::before {
        content: "";
        display: inline-block;
        width: 4px;
        height: 18px;
        background: #409EFF;
        margin-right: 10px;
        border-radius: 2px;
      }
    }

    .subtitle {
      font-size: 14px;
      color: #909399;
      margin: 8px 0 0;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 15px;

    .status-filter {
      width: 180px;

      :deep(.el-input__inner) {
        border-radius: 8px;
      }
    }

    .refresh-btn {
      width: 40px;
      height: 40px;
      font-size: 16px;
      transition: all 0.3s;

      &:hover {
        transform: rotate(360deg);
      }
    }
  }
}

/* 主卡片样式 */
.main-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f2f5;

    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }

    .card-extra {
      font-size: 14px;
      color: #909399;
    }
  }

  .order-table {
    margin-top: 15px;

    :deep(.el-table__header) {
      th {
        font-weight: 600;
      }
    }

    :deep(.el-table__body) {
      tr:hover td {
        background-color: #f5f7fa !important;
      }
    }

    .order-no {
      font-family: 'Courier New', monospace;
      color: #409EFF;
    }

    .price {
      color: #f56c6c;
      font-weight: 500;
    }

    .status-tag {
      padding: 5px 10px;
      border-radius: 4px;
      font-size: 13px;

      .el-button {
        margin-left: 8px;
        padding: 4px 8px;
      }
    }

    .action-buttons {
      display: flex;
      align-items: center;

      .action-btn {
        padding: 5px;
        margin: 0 2px;
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: 3px;
          font-size: 14px;
        }

        &.detail-btn {
          color: #409EFF;

          &:hover {
            color: #66b1ff;
          }
        }

        &.delete-btn {
          color: #f56c6c;

          &:hover {
            color: #f78989;
          }
        }
      }
    }
  }
}

/* 分页样式 */
.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: center;

  .pagination {
    :deep(.btn-prev),
    :deep(.btn-next),
    :deep(.number) {
      border-radius: 6px;
      margin: 0 4px;
    }

    :deep(.number.active) {
      background: #409EFF;
      color: #fff;
    }
  }
}

/* 详情弹窗样式 */
.detail-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;

    .el-dialog__header {
      padding: 15px 20px;
      background: #f5f7fa;
      border-bottom: 1px solid #ebeef5;
      margin-right: 0;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
      }
    }

    .el-dialog__body {
      padding: 20px;
    }
  }

  .dialog-header {
    margin-bottom: 20px;

    h3 {
      font-size: 16px;
      color: #303133;
      margin: 0;
    }
  }

  .detail-table {
    .product-image {
      max-width: 80px;
      max-height: 80px;
      object-fit: contain;
      border-radius: 4px;
      border: 1px solid #ebeef5;
    }

    .price {
      color: #f56c6c;
      font-weight: 500;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}

/* 付款弹窗样式 */
.pay-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;

    .el-dialog__header {
      padding: 15px 20px;
      background: #f5f7fa;
      border-bottom: 1px solid #ebeef5;
      margin-right: 0;
    }
  }

  .pay-content {
    padding: 0 20px;

    .pay-method {
      margin-bottom: 30px;

      :deep(.el-select) {
        width: 100%;
      }

      .pay-option {
        display: flex;
        align-items: center;

        .pay-icon {
          width: 20px;
          height: 20px;
          margin-right: 10px;
        }
      }
    }

    .pay-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 30px;

      .cancel-btn {
        margin-right: 15px;
      }

      .confirm-btn {
        background: #409EFF;
        border-color: #409EFF;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .order-container {
    padding: 15px;
  }

  .header-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .header-content .title {
    font-size: 20px;
  }

  .main-card {
    padding: 15px;

    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
  }

  .detail-dialog {
    :deep(.el-dialog) {
      width: 90% !important;
    }
  }
}
</style>